package com.castle.fortress.admin.system.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.system.dto.SysUserDto;
import com.castle.fortress.admin.system.entity.SysRole;
import com.castle.fortress.admin.system.entity.SysUser;
import com.castle.fortress.admin.system.entity.SysUserRole;
import com.castle.fortress.admin.system.service.SysCaptchaService;
import com.castle.fortress.admin.system.service.SysUserRoleService;
import com.castle.fortress.admin.system.service.SysUserService;
import com.castle.fortress.admin.utils.PwdUtil;
import com.castle.fortress.admin.utils.WebUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.BizErrorCode;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.utils.CommonUtil;
import com.castle.fortress.common.utils.ConvertUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.ArrayList;
import java.util.List;

/**
 * 系统用户管理
 * @author castle
 */
@Api(tags = "系统用户管理控制器")
@Controller
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysCaptchaService sysCaptchaService;

    /**
     * 系统用户表的分页展示 单独处理数据权限
     * @param sysUserDto 系统用户表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @ApiOperation("系统用户表分页展示")
    @GetMapping("/system/sysUser/page")
    @ResponseBody
    @RequiresPermissions("system:sysUser:pageList")
    public RespBody<IPage<SysUserDto>> pageSysUserDto(SysUserDto sysUserDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        SysUser sysUser= WebUtil.currentUser();
        if(sysUser == null){
            throw new BizException(GlobalRespCode.NO_LOGIN_ERROR);
        }
        //不是超管 只能查看普通用户，不可查看超管用户
        if(!sysUser.getIsAdmin()){
            sysUserDto.setIsAdmin(false);
        }
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<SysUserDto> page = new Page(pageIndex, pageSize);
        IPage<SysUserDto> pages = sysUserService.pageExtendsSysUser(page, sysUserDto,sysUser);
        return RespBody.data(pages);
    }

    /**
     * 系统用户表保存
     * @param sysUserDto 系统用户表实体类
     * @return
     */
    @ApiOperation("系统用户表保存")
    @PostMapping("/system/sysUser/save")
    @ResponseBody
    @RequiresPermissions("system:sysUser:save")
    public RespBody<String> saveSysUserDto(@RequestBody SysUserDto sysUserDto){
        if(sysUserDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser sysUser = ConvertUtil.transformObj(sysUserDto,SysUser.class);
        sysUser.setPassword(PwdUtil.encode(sysUser.getPassword()));
        RespBody checkResult = sysUserService.checkColumnRepeat(sysUser);
        if(!checkResult.isSuccess()){
            return checkResult;
        }
        //todo 校验手机号、证件号
        if(sysUserService.save(sysUser)){
            //插入用户角色信息
            if(sysUser.getRoles()!=null && sysUser.getRoles().size()>0){
                List<SysUserRole> userRoleList= new ArrayList<>();
                for(SysRole role:sysUser.getRoles()){
                    SysUserRole userRole = new SysUserRole();
                    userRole.setRoleId(role.getId());
                    userRole.setUserId(sysUser.getId());
                    userRoleList.add(userRole);
                }
                sysUserRoleService.saveBatch(userRoleList);
            }
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 系统用户表编辑
     * @param sysUserDto 系统用户表实体类
     * @return
     */
    @ApiOperation("系统用户表编辑")
    @PostMapping("/system/sysUser/edit")
    @ResponseBody
    @RequiresPermissions("system:sysUser:edit")
    public RespBody<String> updateSysUser(@RequestBody SysUserDto sysUserDto){
        if(sysUserDto == null || sysUserDto.getId() == null || sysUserDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser sysUser = ConvertUtil.transformObj(sysUserDto,SysUser.class);
        if(StrUtil.isNotEmpty(sysUser.getPassword())){
            sysUser.setPassword(PwdUtil.encode(sysUser.getPassword()));
        }else{
            sysUser.setPassword(null);
        }
        RespBody checkResult = sysUserService.checkColumnRepeat(sysUser);
        if(!checkResult.isSuccess()){
            return checkResult;
        }
        if(sysUserService.updateById(sysUser)){
            //删除原有的角色管理
            sysUserRoleService.delByUserId(sysUser.getId());
            //保存新的角色关系
            List<SysUserRole> userRoleList= new ArrayList<>();
            for(SysRole role:sysUser.getRoles()){
                SysUserRole userRole = new SysUserRole();
                userRole.setRoleId(role.getId());
                userRole.setUserId(sysUser.getId());
                userRoleList.add(userRole);
            }
            sysUserRoleService.saveBatch(userRoleList);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 系统用户表删除
     * @param id
     * @return
     */
    @ApiOperation("系统用户表删除")
    @PostMapping("/system/sysUser/delete")
    @ResponseBody
    @RequiresPermissions("system:sysUser:delete")
    public RespBody<String> deleteSysUser(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser user = WebUtil.currentUser();
        if(user.getId().equals(id)){
            return RespBody.fail(BizErrorCode.USER_DEL_SELF_ERROR);
        }
        if(sysUserService.removeById(id)) {
            //删除原有的角色管理
            sysUserRoleService.delByUserId(id);
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 系统用户表详情
     * @param id 系统用户表id
     * @return
     */
    @ApiOperation("系统用户表详情")
    @GetMapping("/system/sysUser/info")
    @ResponseBody
    @RequiresPermissions("system:sysUser:info")
    public RespBody<SysUserDto> infoSysUser(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser sysUser = sysUserService.getByIdExtends(id);
        SysUserDto sysUserDto = ConvertUtil.transformObj(sysUser, SysUserDto.class);
        return RespBody.data(sysUserDto);
    }

    /**
     * 个人设置-信息
     * @return
     */
    @ApiOperation("个人设置-信息")
    @GetMapping("/system/sysUser/personInfo")
    @ResponseBody
    public RespBody<SysUserDto> personInfo(){
        SysUser u = WebUtil.currentUser();
        SysUser sysUser = sysUserService.getByIdExtends(u.getId());
        SysUserDto sysUserDto = ConvertUtil.transformObj(sysUser, SysUserDto.class);
        return RespBody.data(sysUserDto);
    }

    /**
     * 个人设置-更新
     * @param sysUserDto 系统用户表实体类
     * @return
     */
    @ApiOperation("系统用户表编辑")
    @PostMapping("/system/sysUser/personEdit")
    @ResponseBody
    public RespBody<String> personEdit(@RequestBody SysUserDto sysUserDto){
        if(sysUserDto == null || sysUserDto.getId() == null || sysUserDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser u = WebUtil.currentUser();
        if(!u.getId().equals(sysUserDto.getId())){
            throw new BizException(GlobalRespCode.UNAUTHORIZED);
        }
        SysUser sysUser = ConvertUtil.transformObj(sysUserDto,SysUser.class);
        //不修改密码
        sysUser.setPassword(null);
        RespBody checkResult = sysUserService.checkColumnRepeat(sysUser);
        if(!checkResult.isSuccess()){
            return checkResult;
        }
        if(sysUserService.updateById(sysUser)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 个人设置-修改密码
     * @param sysUserDto 系统用户表实体类
     * @return
     */
    @ApiOperation("个人设置-修改密码")
    @PostMapping("/system/sysUser/personUptPwd")
    @ResponseBody
    public RespBody<String> personUptPwd(@RequestBody SysUserDto sysUserDto){
        if(CommonUtil.verifyParamNull(sysUserDto,sysUserDto.getId(),sysUserDto.getPassword(),sysUserDto.getOldPassword())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser u = WebUtil.currentUser();
        if(!u.getId().equals(sysUserDto.getId())){
            throw new BizException(GlobalRespCode.UNAUTHORIZED);
        }
        SysUser su = sysUserService.getById(u.getId());
        //校验原密码
        if(!PwdUtil.matches(sysUserDto.getOldPassword(),su.getPassword())){
            throw new BizException(BizErrorCode.OLD_PWD_ERROR);
        }
        SysUser uptUser = new SysUser();
        uptUser.setId(u.getId());
        uptUser.setPassword(PwdUtil.encode(sysUserDto.getPassword()));
        if(sysUserService.updateById(uptUser)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 个人设置-修改手机号
     * @param sysUserDto 系统用户表实体类
     * @return
     */
    @ApiOperation("个人设置-修改手机号")
    @PostMapping("/system/sysUser/personUptPhone")
    @ResponseBody
    public RespBody<String> personUptPhone(@RequestBody SysUserDto sysUserDto){
        if(CommonUtil.verifyParamNull(sysUserDto,sysUserDto.getId(),sysUserDto.getPhone(),sysUserDto.getOldPhone(),sysUserDto.getCaptcha(),sysUserDto.getOldCaptcha())){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        SysUser u = WebUtil.currentUser();
        if(!u.getId().equals(sysUserDto.getId())){
            throw new BizException(GlobalRespCode.UNAUTHORIZED);
        }
        SysUser su = sysUserService.getById(u.getId());
        //校验原手机号
        if(!su.getPhone().equals(sysUserDto.getOldPhone())){
            throw new BizException(BizErrorCode.OLD_PHONE_ERROR);
        }
        //校验验证码
        sysCaptchaService.verifySysCaptcha(sysUserDto.getPhone(),sysUserDto.getCaptcha());
        //校验验证码
        sysCaptchaService.verifySysCaptcha(sysUserDto.getOldPhone(),sysUserDto.getOldCaptcha());
        //校验新手机号是否占用
        su.setPhone(sysUserDto.getPhone());
        RespBody repeatRb = sysUserService.checkColumnRepeat(su);
        if(repeatRb.isSuccess()){
            SysUser uptUser = new SysUser();
            uptUser.setId(u.getId());
            uptUser.setPhone(sysUserDto.getPhone());
            if(sysUserService.updateById(uptUser)){
                return RespBody.data("保存成功");
            }else{
                return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
            }
        }else{
            return repeatRb;
        }
    }
}
